Imports System.ComponentModel

Public Interface IChildObjectWrapperBase
	Inherits IWrapper

	Function GetRootObject() As RootObjectWrapperBase
End Interface

Public Class ChildObjectWrapperBase
	Inherits WrapperBase
	Implements IChildObjectWrapperBase

	Private m_RootObject As RootObjectWrapperBase
	Protected Friend ReadOnly Property RootObject() As RootObjectWrapperBase
		Get
			Return Me.m_RootObject
		End Get
	End Property

	Private Function GetRootObject() As RootObjectWrapperBase Implements IChildObjectWrapperBase.GetRootObject
		Return Me.RootObject
	End Function

	Protected Friend Function FindTopRootObject() As RootObjectWrapperBase
		Dim curRoot As RootObjectWrapperBase = Me.RootObject
		Dim tmpRoot As RootObjectWrapperBase = curRoot

		While Not tmpRoot Is Nothing
			curRoot = tmpRoot
			If TypeOf tmpRoot Is IChildObjectWrapperBase Then
				Dim tmpChild As IChildObjectWrapperBase = tmpRoot
				tmpRoot = tmpChild.GetRootObject()
			End If
		End While

		Return curRoot
	End Function

	Protected Overrides Sub DisposeInternal()
		MyBase.DisposeInternal()

		Dim rootObject As RootObjectWrapperBase = Me.m_RootObject
		Me.m_RootObject = Nothing
		If rootObject IsNot Nothing Then
			rootObject.ChildObjects.Remove(Me)
		End If
	End Sub

	<Description("Construcotr.")> _
	Public Sub New(<Description("Native (COM+) object.")> ByVal nativeObject As Object, ByVal rootObject As RootObjectWrapperBase)
		MyBase.New(nativeObject)

		If rootObject Is Nothing Then Throw New ArgumentNullException("rootObject")
		Me.m_RootObject = rootObject
		rootObject.ChildObjects.Add(Me)
	End Sub
End Class
